#include "dtwentymodel.h"


#include <QFile>


DTwentyModel::DTwentyModel(QObject *parent) :
    ItemTreeModel(parent)
{
    qRegisterMetaType<Campaign*>("Campaign");
}

DTwentyModel::DTwentyModel(Campaign *campaign, QObject *parent) :
    ItemTreeModel(campaign, parent)
{
    qRegisterMetaType<Campaign*>("Campaign");
}


QString DTwentyModel::campaignName() const
{
    Campaign* c = campaign();
    if (!c)
    {
        return QString();
    }

    return c->name();
}

void DTwentyModel::setCampaignName(const QString &name)
{
    Campaign* c = campaign();
    if (!c)
    {
        return;
    }

    c->setName(name);
}


bool DTwentyModel::insertRows(int row, int count, const QModelIndex &parent)
{
    Q_UNUSED(row)
    Q_UNUSED(count)

    DTwentyItem* parentItem = qobject_cast<DTwentyItem*>(itemFromIndex(parent));

    if (parentItem->childType() < 0)
    {
        return false;
    }

    DTwentyItem* item = DTwentyItemFactory::create(parentItem->childType(), parentItem);
    if (!item)
    {
        return false;
    }

    QString typeName = item->metaObject()->className();
    item->setName(QString("%1 %2").arg(QT_TR_NOOP("New")).arg(typeName));

    return true;
}

bool DTwentyModel::removeRows(int row, int count, const QModelIndex &parent)
{
    Q_UNUSED(count)

    DTwentyItem* parentItem = qobject_cast<DTwentyItem*>(itemFromIndex(parent));

    if (parentItem->childType() < 0)
    {
        return false;
    }

    QList<DTwentyItem*> itemList = parentItem->findChildren<DTwentyItem*>("", Qt::FindDirectChildrenOnly);
    if (row < 0 || row >= itemList.count())
    {
        return false;
    }

    DTwentyItem* item = itemList.at(row);
    item->setParent(0);
    item->deleteLater();

    return true;
}

Campaign *DTwentyModel::campaign() const
{
    return qobject_cast<Campaign*>(root());
}


